<?php
namespace backend\controllers\rbac;
Use common\models\RbacResource;
use backend\controllers\BackendBase;
use common\models\RbacResourceUri;
use yii\helpers\Json;

class ResourceController extends BackendBase
{
    public function actionIndex(){
        if(!$this->isJson){
            return $this->renderView('/rbac/resource/index');
        }
        return $this->page( RbacResource::find() ) ;
    }

    public function actionAll(){
        return RbacResource::find()->all();
    }

    public function actionUri(){
        $resource_id = $this->request()->get('resource_id',0) ;
        return RbacResourceUri::find()->where(['resource_id' => $resource_id])->all() ;
    }


    public function actionSave(){
        $id = $this->request()->get('id',0);
        if(!$this->isPost){
            $data = '""' ;
            if($id){
                $model = RbacResource::findOne($id) ;
                $data = Json::encode($model);
            }
            return $this->renderView('/rbac/resource/save',['data' => $data]);
        }

        $data = $this->request()->post() ;

        if($id){
            $model = RbacResource::findOne($id);
        }else{
            $model = new RbacResource();
        }

        if($model->load($data,'') && $model->save()){
            $model->saveUris($data['uris']) ;
            return true ;
        }else{
            return $model->getErrors() ;
        }
    }


    public function actionDelete(){
        $id = $this->request()->get('id',0);
        $isDelete = RbacResource::findOne($id)->delete();
        return ['code' => 0];
    }
}